<template>

  <!--  卡片区域  -->
  <n-card>
    <!--    工具栏    -->
    <n-space justify="end" style="padding-bottom: 15px;">
      <!--  新建按钮    -->
      <n-button @click="showModal = true" type="info" style="width: 80px; height: 30px">
        <n-icon size="18">
          <add/>
        </n-icon>
        新建
      </n-button>
      <!--刷新-->
      <n-tooltip trigger="hover">
        <template #trigger>
          <n-button text style="font-size: 20px; width:22px; height:32px;" @click="refresh">
            <n-icon>
              <refresh-sharp />
            </n-icon>
          </n-button>
        </template>
        <span>刷新</span>
      </n-tooltip>
      <!--密度-->
      <n-popselect v-model:value="densityValue" :options="densityOptions" trigger="click">
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button text style="font-size: 20px; width:22px; height:32px; margin-left: 11px">
              <n-icon>
                <auto-fit-height20-regular />
              </n-icon>
            </n-button>
          </template>
          <span>密度</span>
        </n-tooltip>
      </n-popselect>
      <!--列设置-->
      <n-tooltip trigger="hover">
        <template #trigger>
          <n-popover trigger="click" placement="bottom-end">
            <template #trigger>
              <n-button text style="font-size: 20px; width:22px; height:32px; margin-bottom: 2px; margin-left: 11px">
                <n-icon>
                  <Settings20Regular />
                </n-icon>
              </n-button>
            </template>
            <template #header>
              <n-checkbox label="列展示" v-model:checked="allChecked" @update:checked="allChange" />
            </template>
            <n-space vertical>
              <n-checkbox v-for="item in checkboxList" :key="item.name" :label="item.name" v-model:checked="item.checked" @update:checked="itemChange" />
            </n-space>
          </n-popover>
        </template>
        <span>列设置</span>
      </n-tooltip>
    </n-space>
    <!--    数据表格    -->
    <n-data-table
        :columns="columns"
        :data="data"
        :pagination="pagination"
        :bordered="false"
        :size="densityValue"
        :loading="loading"
    />
  </n-card>
  <!--  打开的拟态框  -->
  <n-modal v-model:show="showModal" preset="card" :style="bodyStyle" title="添加" :segmented="segmented">
    <!--表单-->
    <n-form :rules="rules" :model="formValue">
      <n-form-item path="user.name" label="图片名称">
        <n-input
            clearable
            v-model:value="formValue.user.name"
            placeholder="请输入名称"
        >
        </n-input>
      </n-form-item>
      <n-form-item label="是否启用">
        <n-select
            v-model:value="enableValue"
            :options="enable_status"
            placeholder="请选择是否启用"
            clearable
        />
      </n-form-item>
      <n-form-item path="user.href" label="图片跳转地址">
        <n-input
            clearable
            v-model:value="formValue.user.href"
            placeholder="请输入图片跳转地址"
        >
        </n-input>
      </n-form-item>
      <n-form-item label="跳转类型">
        <n-select
            v-model:value="typeValue"
            :options="type"
            placeholder="请选择图片跳转类型"
            clearable
        />
      </n-form-item>
      <n-form-item path="user.weight" label="推荐值(0为未推荐)">
        <n-input-number
            v-model:value="formValue.user.weight"
            placeholder="请输入"
        >
        </n-input-number>
      </n-form-item>
      <n-form-item label="上传图片">
        <n-upload list-type="image-card">
          <n-space vertical>
            <n-icon size="18">
              <add/>
            </n-icon>
            上传图片
          </n-space>
        </n-upload>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancel">取消</n-button>
        <n-button type="info" @click="sure">确定</n-button>
      </n-space>
    </template>
  </n-modal>
  <n-modal v-model:show="showEditModal" preset="card" :style="bodyStyle" title="添加" :segmented="segmented">
    <!--表单-->
    <n-form :rules="rules" :model="formEditValue">
      <n-form-item path="user.name" label="图片名称">
        <n-input
            clearable
            v-model:value="formEditValue.user.name"
            placeholder="请输入名称"
        >
        </n-input>
      </n-form-item>
      <n-form-item label="是否启用">
        <n-select
            v-model:value="enableEditValue"
            :options="enable_status"
            placeholder="请选择是否启用"
            clearable
        />
      </n-form-item>
      <n-form-item path="user.href" label="图片跳转地址">
        <n-input
            clearable
            v-model:value="formEditValue.user.href"
            placeholder="请输入图片跳转地址"
        >
        </n-input>
      </n-form-item>
      <n-form-item label="跳转类型">
        <n-select
            v-model:value="typeValue"
            :options="type"
            placeholder="请选择图片跳转类型"
            clearable
        />
      </n-form-item>
      <n-form-item path="user.weight" label="推荐值(0为未推荐)">
        <n-input-number
            v-model:value="formEditValue.user.weight"
            placeholder="请输入"
        >
        </n-input-number>
      </n-form-item>
      <n-form-item label="上传图片">
        <n-upload list-type="image-card">
          <n-space vertical>
            <n-icon size="18">
              <add/>
            </n-icon>
            上传图片
          </n-space>
        </n-upload>
      </n-form-item>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="cancelEdit">取消</n-button>
        <n-button type="info" @click="sureEdit">确定</n-button>
      </n-space>
    </template>
  </n-modal>

</template>

<script>
import {defineComponent, h, reactive, ref} from 'vue'
import {NButton, NForm, NFormItem, NInput, NTag, NFlex, NIcon, NImage, NText} from "naive-ui";
import { Add } from "@vicons/ionicons5"
import { RefreshSharp } from "@vicons/material"
import { AutoFitHeight20Regular ,Settings20Regular} from "@vicons/fluent"
import { LeftOutlined , RightOutlined} from "@vicons/antd"
import { GetBannerList, AddBanner, UpdateBanner, DeleteBanner } from "@/api/banner";

export default defineComponent({
  components: {
    Add,
    RefreshSharp,
    AutoFitHeight20Regular,
    Settings20Regular,
    LeftOutlined,
    RightOutlined
  },
  setup(){
    const message = window.$message
    const dialog = window.$dialog
    // 加载
    const loading = ref(false)

    /*  数据表格  */
    // 创建表格列模版
    const createColumns = () => {
      return [
        {
          title: "序号",
          key: "index",
          render(row, index) {
            return index + 1;
          }
        },
        {
          title: "名称",
          key: "name"
        },
        {
          title: "图片地址",
          key: "avatar",
          render(row) {
            return h(NImage, {
              src: row.avatar ? row.avatar : 'https://recruit.aicase.xyz/storage/images/boss_avatar/'+row.id,
              width: 30,
              alt: ' ',
            });
          }
        },
        {
          title: "图片跳转链接类型",
          key: "type",
          render(row) {
            return h(
                NText, {}, { default: () => row.type === 1 ? "(微信内部)" : "http(外部)" });
          }
        },
        {
          title: "图片跳转地址",
          key: "href"
        },
        {
          title: "是否启用",
          key: "status",
          render(row) {
            return h(
                NText, {}, { default: () => row.status === 1 ? "启用" : "禁用" });
          }
        },
        {
          title: "推荐值",
          key: "weight",
        },
        {
          title: "操作",
          key: "actions",
          render(row) {
            return h(
                NFlex,
                {
                  size: "small",
                },
                {
                  default: () => [
                    h(
                        NButton,
                        {
                          text: true,
                          color: "#3FA2FE",
                          onClick: () => {
                            console.log(row)
                            showEditModal.value = true
                            formEditValue.value.user.name = row.name
                            formEditValue.value.user.url = row.avatar
                            formEditValue.value.user.href = row.href
                            formEditValue.value.user.weight = row.weight
                            formEditValue.value.user.id = row.id
                            enableEditValue.value = row.status
                            typeValue.value = row.type
                          }
                        },
                        { default: () => "编辑" }
                    ),
                    h(
                        NButton,
                        {
                          text: true,
                          color: "#3FA2FE",
                          onClick: () => {
                            dialog.warning({
                              title: '删除记录',
                              content: '确定删除该记录吗？',
                              positiveText: '确定',
                              negativeText: '取消',
                              maskClosable: false,
                              onNegativeClick: () => {
                                message.success('取消删除')
                              },
                              onPositiveClick: () => {
                                message.success('确定删除')
                                DeleteBanner(row.id).then(res => {
                                  console.log(res)
                                  if (res.code === 0) {
                                    message.success(res.message)
                                    // 更新数据
                                    window.location.reload()
                                  } else {
                                    message.error(res.message)
                                  }
                                })

                              }
                            })


                          }
                        },
                        { default: () => "删除" }
                    )
                  ]
                }
            )
          }
        }
      ];
    };
    const columns = createColumns()
    // 表格数据
    let data = reactive([])
    // 总条数
    const total = ref(0);
    // 总页数
    const totalPage = ref(0);
    // 当前页
    const page = ref(0);
    // 当前获取数据最后一页
    // const lastPage = ref(1);
    // 分页设置
    const pagination = {
      prev:()=>{
        return h(
            NIcon,
            {
              onClick:()=>{
                if (page.value > 1) {
                  page.value --
                }
              }
            },
            {
              default: () => h(LeftOutlined)
            }
        )
      },
      next:()=>{
        return h(
            NIcon,
            {
              onClick:()=>{
                if (page.value < totalPage.value) {
                  page.value ++
                }
              }
            },
            {
              default: () => h(RightOutlined)
            }
        )
      },
      prefix:()=>{
        const range = [page.value * 10 - 9, page.value * 10];
        if (page.value === 0) {
          return `第 0 - 0 条 / 总共 ${total.value} 条`
        }else if (page.value === 1 && totalPage.value !== 1) {
          return `第 1 - ${range[1]} 条 / 总共 ${total.value} 条`;
        }else if (page.value === totalPage.value) {
          return `第 ${range[0]} - ${data.length} 条 / 总共 ${total.value} 条`;
        }else if (page.value > 1 && page.value < totalPage.value) {
          return `第 ${range[0]} - ${range[1]} 条 / 总共 ${total.value} 条`;
        }
      },
    }

    /*获取用户列表数据*/
    let getData = ()=>{
      let per_page = ref(100)
      const param = {
        page:page.value,
        per_page:per_page.value
      }
      loading.value = true
      GetBannerList().then(res => {
        // 转换数据库时间格式为标准时间格式方法
        let getDate = (time)=> {
          const dateTime = new Date(time)
          const year = dateTime.getFullYear()
          let month = (dateTime.getMonth() + 1)
          month =  month >= 10 ? month: `0${month}`
          let date = dateTime.getDate()
          date = date >= 10? date : `0${date}`
          let hour = dateTime.getHours()
          hour = hour >= 10? hour : `0${hour}`
          let minute = dateTime.getMinutes()
          minute = minute >= 10? minute : `0${minute}`
          let second = dateTime.getSeconds()
          second = second >= 10? second : `0${second}`
          return `${year}-${month}-${date} ${hour}:${minute}:${second}`
        }
        console.log(res)
        const content = res.data.list
        console.log(content)
        content.forEach((item, index) => {
          data.push({
            id: item.id,
            key: index,
            name: item.name,
            avatar: item.url,
            type: item.type,
            href: item.href? item.href : '-',
            status: item.enable_status,
            weight: item.weight,
            time: getDate(item.created_at)
          })
        })
        total.value = res.meta.total
        // totalPage.value = Math.ceil(total.value / 10)
        totalPage.value = Math.ceil(data.length / 10)
        // lastPage.value = Math.ceil(data.length / 10)
        page.value = 1
        loading.value = false
      })
    }
    // 调用数据
    getData()


    /*  工具栏  */
    /*新建*/
    // 显示新建-模态框
    const showModal = ref(false)
    // 显示编辑-模态框
    const showEditModal = ref(false)
    // 模态框样式
    const bodyStyle = {
      width: "640px",
    }
    const segmented = {
      content: "soft",
      footer: "soft"
    }
    // 取消新建-模态框
    function cancel() {
      showModal.value = false
    }
    // 取消编辑-模态框
    function cancelEdit() {
      showEditModal.value = false
    }
    // 新建-确定提交
    // 确定提交
    function sure() {
      let formData = {
        name: formValue.value.user.name,
        url: formValue.value.user.url,
        href: formValue.value.user.href,
        weight: formValue.value.user.weight,
        enable_status: enableValue.value,
        type: typeValue.value
      }
      AddBanner(formData).then(res => {
        console.log(res)
        if (res.code === 0) {
          message.success(res.message)
          cancel()
          // 刷新数据
          window.location.reload()
        } else {
          message.error(res.message)
        }
      })

    }
    // 编辑-确定提交
    function sureEdit() {
      let formData = {
        id: formEditValue.value.user.id,
        name: formEditValue.value.user.name,
        url: formEditValue.value.user.url,
        href: formEditValue.value.user.href,
        weight: formEditValue.value.user.weight,
        enable_status: enableEditValue.value,
        type: typeValue.value
      }
      UpdateBanner(formData).then(res => {
        console.log(res)
        if (res.code === 0) {
          message.success(res.message)
          cancel()
          // 刷新数据
          window.location.reload()
        } else {
          message.error(res.message)
        }
      })
    }

    // 表单信息
    const formValue = ref({
      user: {
        name: "",
        url: "/storage/images/banner/",
        href: "",
        weight: 0
      }
    })
    // 编辑-表单信息
    const formEditValue = ref({
      user: {
        id: "",
        name: "",
        url: "/storage/images/banner/",
        href: "",
        weight: 0
      }
    })
    // 新建-账号状态
    const enableValue = ref()
    // 编辑-账号状态
    const enableEditValue = ref()
    // 账号状态列表
    const enable_status = ref([
      {label: "启用", value: 1},
      {label: "关闭", value: 0},
    ])
    // 图片跳转链接类型
    const typeValue = ref()
    const type = ref([
      {label: "http类型", value: 1},
      {label: "公众号类型", value: 0},
    ])

    // 验证规则
    const rules = {
      user: {
        name: {
          required: true,
          trigger: "blur",
          message: "请输入名称",
        },
        href: {
          required: true,
          trigger: "blur",
          message: "请输入图片跳转地址",
        },
        weight: {
          required: true,
          trigger: "blur",
          message: "请设置推荐值",
        },
      }
    };

    /*刷新*/
    // 刷新
    function refresh() {
      window.location.reload()
    }

    /*密度*/
    // 密度事件数据
    const densityOptions = [
      {
        label: "默认",
        value: "large"
      },
      {
        label: "中等",
        value: "medium"
      },
      {
        label: "紧密",
        value: "small",
      },
    ]
    const densityValue = ref('medium')

    /*列设置*/
    // 复选框全选
    const allChecked = ref(true)
    // 复选框列表
    const checkboxList = ref([])
    // 列表添加数据
    for (let i = 0;i < columns.length; i++){
      checkboxList.value.push({name: columns[i].title, checked: true})
    }
    // 全选改变事件
    const allChange = ()=>{
      if (allChecked.value) {
        checkboxList.value.forEach(item => {item.checked = true})
      } else {
        checkboxList.value.forEach(item => {item.checked = false})
      }
    }
    // 复选框单个改变事件
    const itemChange = ()=>{
      if (checkboxList.value.every(item => item.checked)) {
        allChecked.value = true
      } else {
        allChecked.value = false
      }
    }


    return {
      showModal,
      showEditModal,
      bodyStyle,
      segmented,
      cancel,
      cancelEdit,
      sure,
      sureEdit,
      formValue,
      formEditValue,
      rules,
      enableValue,
      enableEditValue,
      enable_status,
      type,
      typeValue,
      densityOptions,
      densityValue,
      data,
      columns,
      pagination,
      loading,
      refresh,
      page,
      checkboxList,
      allChecked,
      allChange,
      itemChange


    }
  }

})
</script>

<style scoped>

</style>